VBcoders Guest



Don't have an account yet? Register
 


Forgot Password?



Solves the cubic equation ax^3 + bx^2 + cx + d = 0

by RedSting71 (9 Submissions)
Category: Math/Dates
Compatability: VB 6.0
Difficulty: Unknown Difficulty
Originally Published: Sun 7th July 2002
Date Added: Mon 8th February 2021
Rating: (1 Votes)

Solves the cubic equation ax^3 + bx^2 + cx + d = 0

API Declarations


'Considerably more complicated (and harder to program) than solving the quadratc

Rate Solves the cubic equation ax^3 + bx^2 + cx + d = 0



'Let a, b, c, d be the respective coefficients in the cubic ax^3 + bx^2 + cx + d = 0
If Val(A) = 0 Then MsgBox "Coefficient of cubic term cannot equal 0!", vbCritical, "Error!": Exit Sub 'Make sure its a cubic we're solving
b = b / A: c = c / A: d = d / A 'Get rid of the coefficient of x cubed
A = b
b = c
c = d 'Just a lil renaming
If (A ^ 2 - 3 * b) = 0 Then    'Easy situation
    x1 = (-A / 3) + (A ^ 3 / 27 - c) ^ (1 / 3)
    'This is the only real solution, so we can forget about the others
    Math_SolveCubic = str(x1)
Exit Sub
End If
If (A ^ 2 - 3 * b) <> 0 Then 'More complex here
    g = A ^ 2 - 3 * b       'Define auxiliary variables
    h = A * b - 9 * c
    i = b ^ 2 - 3 * A * c
    Z = (-h + Sqr(h ^ 2 - 4 * g * i)) / (2 * g)  'The big variable, z, defined in other variables, defined in the original variables...
    'At this point we have a quadratic equation - if the formula for z looks familiar, that's why
    'Now use Z to get 3 more variables
    d = 3 * Z + A
    e = 3 * Z ^ 2 + 2 * A * Z + b
    f = Z ^ 3 + A * Z ^ 2 + b * Z + c 'At this point defining everything in terms of the original coefficients would be endless!
    Y = 3 * f / (-e + (e ^ 3 - 27 * f ^ 2) ^ (1 / 3)) 'Now d,e,f is used to define Y
    'And y finally gives us an original root, x
    x1 = Z + 3 * f / ((e ^ 3 - 27 * f ^ 2) & (1 / 3) - e)
    'The other two roots can be real or not real, but they require imaginary roots to solve, so forget about them
    Math_SolveCubic = str(x1)
    End If
End Function

Download this snippet    Add to My Saved Code

Solves the cubic equation ax^3 + bx^2 + cx + d = 0 Comments

No comments have been posted about Solves the cubic equation ax^3 + bx^2 + cx + d = 0. Why not be the first to post a comment about Solves the cubic equation ax^3 + bx^2 + cx + d = 0.

Post your comment

Subject:
Message:
0/1000 characters